//
//  MyJoinClubDetailVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/16.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "MyJoinClubDetailVC.h"
#import "MyJoinClubDetailCell.h"
#import "ClubListTipsVC.h"
#import "SetUpMessBoardVC.h"
#import "ActivityDetailVC.h"

@interface MyJoinClubDetailVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@end

@implementation MyJoinClubDetailVC
{
    UICollectionView *_collectionView;
    UIView *_view;
    
    NSDictionary *_responseDic;
    NSArray *_responseArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LighterGrayColor;
    self.title = @"俱乐部详情";
    [self requestForClubActivity];
    [self initCollectionView];
    [self initRigthView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"button_club"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtn)];
}
#pragma - mark 根据俱乐部ID请求该俱乐部的热门活动
- (void)requestForClubActivity{
    //参数
    NSDictionary *parameters = @{
                                 @"clubId": self.clubId,
                                 @"status": @"1",
                                 @"pageNum": @"1",
                                 @"pageSize": @"10",
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/list.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@<<<<>>>>",_responseDic);
        _responseArr = _responseDic[@"list"];
        if ([_responseDic[@"code"] isEqualToString:@"3003"]) {
            [SVProgressHUD showImage:nil status:@"该俱乐部暂时没有热门活动"];
        }else{
            [_collectionView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求活动列表失败"];
    }];
}
- (void)initCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置整个collectionView的内边距
    CGFloat paddingY = 10;
    CGFloat paddingX = 10;
    layout.sectionInset = UIEdgeInsetsMake(paddingY, paddingX, paddingY, paddingX);
    //设置每个格子的尺寸
    layout.itemSize = CGSizeMake(KScreenWidth/2 - 20, 130);
    //设置headerView
    [layout setHeaderReferenceSize:CGSizeMake(KScreenWidth, 130)];
    //设置对齐方式
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight ) collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    //
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(panGestFinger:)];
    tapGest.numberOfTapsRequired = 2;
    [_collectionView addGestureRecognizer:tapGest];
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"];
    //俱乐部信息展示
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 96)];
    bgView.backgroundColor = superBackgroundColor;
    [_collectionView addSubview:bgView];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 70, 70)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.clubIconStr] placeholderImage:[UIImage imageNamed:@"userIcon"]];
    [bgView addSubview:imageView];
    UILabel *nameLb = [[UILabel alloc]initWithFrame:CGRectMake(90, 10, 160, 20)];
    nameLb.textColor = Theme_Color;
    nameLb.text = self.clubName;
    [bgView addSubview:nameLb];
    UIButton *joinBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth - 80, 7, 60, 25)];
    if (self.isJoined == YES) {
        [joinBtn setTitle:@"退出" forState:UIControlStateNormal];
        [joinBtn addTarget:self action:@selector(requestForAgreeJoinClub) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [joinBtn setTitle:@"＋加入" forState:UIControlStateNormal];
        [joinBtn addTarget:self action:@selector(joinAction) forControlEvents:UIControlEventTouchUpInside];
    }
    joinBtn.backgroundColor = Orange_Color;
    [joinBtn setTitleColor:White_Color forState:UIControlStateNormal];
    joinBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    joinBtn.layer.cornerRadius = 3;
    [bgView addSubview:joinBtn];
    UILabel *introLb = [[UILabel alloc]initWithFrame:CGRectMake(90, 30, KScreenWidth - 100, 55)];
    introLb.text = self.clubSummary;
    introLb.numberOfLines = 0;
    introLb.font = [UIFont systemFontOfSize:10];
    [bgView addSubview:introLb];

    //火热报名中的label
    UILabel *baomingLb = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, KScreenWidth - 100, 30)];
    baomingLb.textAlignment = NSTextAlignmentCenter;
    baomingLb.font = [UIFont systemFontOfSize:12];
    baomingLb.text = @"热门活动";
    baomingLb.textColor = Orange_Color;
    [_collectionView addSubview:baomingLb];
}
#pragma mark -- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _responseArr.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIDa = @"MyCollectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIDa forIndexPath:indexPath];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth/2 - 20, 100)];
    NSString *urlStr = _responseArr[indexPath.row][@"coverImgURL"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"picture_10"]];
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    [cell.contentView addSubview:imageView];
    
    UILabel *cityName = [[UILabel alloc]initWithFrame:CGRectMake(8, 100, 129, 20)];
    cityName.text = _responseArr[indexPath.row][@"title"];
    cityName.textColor = Theme_Color;
    cityName.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:cityName];
    
    UILabel *jianjieLb = [[UILabel alloc]initWithFrame:CGRectMake(8, 118, 129, 20)];
    jianjieLb.text = _responseArr[indexPath.row][@"gotoReason"];
    jianjieLb.textColor = [UIColor grayColor];
    jianjieLb.font = [UIFont systemFontOfSize:10];
    [cell.contentView addSubview:jianjieLb];
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ActivityDetailVC *vc = [[ActivityDetailVC alloc]init];
    vc.status = @"1";
    vc.activityId = _responseArr[indexPath.row][@"id"];
    vc.activityHtmlUrlStr = _responseArr[indexPath.row][@"htmlUrl"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)initRigthView{
    _view = [[UIView alloc]initWithFrame:CGRectMake(KScreenWidth - 85, 70, 80, 60)];
    _view.backgroundColor = White_Color;
    _view.layer.cornerRadius = 3;
    _view.layer.borderWidth = 1;
    _view.layer.borderColor = LightGray_Color.CGColor;
    [self.view addSubview:_view];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(10, 30, 60, 1)];
    lineView.backgroundColor = LightGray_Color;
    [_view addSubview:lineView];
    UIButton *mesBoardBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 60, 30)];
    [mesBoardBtn setTitle:@"留言板" forState:UIControlStateNormal];
    [mesBoardBtn addTarget:self action:@selector(messBoardBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [mesBoardBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    mesBoardBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_view addSubview:mesBoardBtn];
    UIButton *tipsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 60, 30)];
    [tipsBtn setTitle:@"旅游Tips" forState:UIControlStateNormal];
    [tipsBtn addTarget:self action:@selector(tipsBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [tipsBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    tipsBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_view addSubview:tipsBtn];
    //先隐藏
    _view.hidden = YES;
}
- (void)rightBtn{
    _view.hidden = !_view.hidden;
}
- (void)joinAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"加入该俱乐部需要满足的条件：参与由该俱乐部发起的活动\n3起及其以上" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"暂不符合" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        //
        
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"满足条件" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        //
        [self requsetForJoinClub];
        
    }];
    [alertController addAction:deleteAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma - mark 加入或退出俱乐部网络请求
//加入俱乐部
- (void)requsetForJoinClub{
    //参数
    NSDictionary *parameters = @{
                                 @"userID": [NSString readToNSDefaultsWithKey:kId],
                                 @"clubID":self.clubId,
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/club/joinClub.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSDictionary *_responseDicForJoin = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDicForJoin);
        NSString *error = _responseDicForJoin[@"code"];
        if (![_responseDicForJoin[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            
        }else{
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"加入成功"];
            [_collectionView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加入失败"];
    }];
}
//退出俱乐部 1.先审核通过之前会员加入俱乐部的申请 2.再退出俱乐部
- (void)requestForAgreeJoinClub{
    //参数
    NSDictionary *parameters = @{
                                 @"userID": [NSString readToNSDefaultsWithKey:kId],
                                 @"clubID":self.clubId,
                                 @"status":@"1",
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/club/auditUser.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSDictionary *_responseDicForOut = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString *error = _responseDicForOut[@"code"];
        if (![_responseDicForOut[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            
        }else{
            //请求成功
            [self signOutBtnAction];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"审核失败"];
    }];
}
- (void)signOutBtnAction{
    //参数
    NSDictionary *parameters = @{
                                 @"userID": [NSString readToNSDefaultsWithKey:kId],
                                 @"clubID":self.clubId,
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/club/quitClub.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSDictionary *_responseDicForSignOut = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDicForSignOut);
        NSString *error = _responseDicForSignOut[@"code"];
        if (![_responseDicForSignOut[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"退出成功"];
            [_collectionView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"退出失败"];
    }];
}
- (void)messBoardBtnAction{
    _view.hidden = YES;
    SetUpMessBoardVC *vc = [[SetUpMessBoardVC alloc]init];
    vc.clubId = self.clubId;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)tipsBtnAction{
    _view.hidden = YES;
    ClubListTipsVC *vc = [[ClubListTipsVC alloc]init];
    vc.clubId = self.clubId;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)panGestFinger:(UITapGestureRecognizer *)sender{
    _view.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
